use std::fmt::Debug;
use std::sync::Arc;
use async_trait::async_trait;
use anyhow::Result;
use serde::{Deserialize, Serialize};
use tracing::{debug, error, info, warn};
use dashmap::DashMap;

use super::{EventStore, PersistenceError, PersistentEvent, PersistentState};

/// 内存存储的事件存储实现
pub struct InMemoryEventStore<E, S>
where
    E: PersistentEvent + for<'de> Deserialize<'de> + Serialize + Clone,
    S: PersistentState + for<'de> Deserialize<'de> + Serialize + Clone,
{
    /// Events storage, indexed by actor_id and then by index
    events: DashMap<String, Vec<E>>,
    
    /// Snapshots storage, indexed by actor_id
    snapshots: DashMap<String, S>,
    
    /// Snapshot interval (0 means no snapshots)
    snapshot_interval: u64,
}

impl<E, S> InMemoryEventStore<E, S>
where
    E: PersistentEvent + for<'de> Deserialize<'de> + Serialize + Clone,
    S: PersistentState + for<'de> Deserialize<'de> + Serialize + Clone,
{
    /// Create a new in-memory event store
    pub fn new(snapshot_interval: u64) -> Self {
        Self {
            events: DashMap::new(),
            snapshots: DashMap::new(),
            snapshot_interval,
        }
    }
}

#[async_trait]
impl<E, S> EventStore for InMemoryEventStore<E, S>
where
    E: PersistentEvent + for<'de> Deserialize<'de> + Serialize + Clone + Debug + 'static,
    S: PersistentState + for<'de> Deserialize<'de> + Serialize + Clone + Debug + 'static,
{
    type Event = E;
    type State = S;
    
    async fn save_event(&self, actor_id: &str, event: &Self::Event, index: u64) -> Result<(), PersistenceError> {
        let mut events_entry = self.events.entry(actor_id.to_string()).or_insert(Vec::new());
        
        // Ensure we have space for the event at the correct index
        if events_entry.len() <= index as usize {
            events_entry.resize_with(index as usize + 1, || {
                panic!("InMemoryEventStore should not resize with events")
            });
        }
        
        // Insert the event at the correct index
        if let Some(existing) = events_entry.get_mut(index as usize) {
            *existing = event.clone();
        } else {
            events_entry.push(event.clone());
        }
        
        debug!("Saved event for actor {}, index {}", actor_id, index);
        Ok(())
    }
    
    async fn get_events(&self, actor_id: &str, start_index: u64) -> Result<Vec<Self::Event>, PersistenceError> {
        if let Some(events) = self.events.get(actor_id) {
            // Return events starting from start_index
            let events = events.value()
                .iter()
                .skip(start_index as usize)
                .cloned()
                .collect::<Vec<_>>();
            
            debug!("Retrieved {} events for actor {} from index {}", events.len(), actor_id, start_index);
            Ok(events)
        } else {
            debug!("No events found for actor {}", actor_id);
            Ok(Vec::new())
        }
    }
    
    async fn save_snapshot(&self, actor_id: &str, state: &Self::State) -> Result<(), PersistenceError> {
        self.snapshots.insert(actor_id.to_string(), state.clone());
        
        debug!("Saved snapshot for actor {}", actor_id);
        Ok(())
    }
    
    async fn get_snapshot(&self, actor_id: &str) -> Result<Option<Self::State>, PersistenceError> {
        if let Some(snapshot) = self.snapshots.get(actor_id) {
            debug!("Retrieved snapshot for actor {}", actor_id);
            Ok(Some(snapshot.clone()))
        } else {
            debug!("No snapshot found for actor {}", actor_id);
            Ok(None)
        }
    }
    
    async fn delete_events(&self, actor_id: &str) -> Result<(), PersistenceError> {
        self.events.remove(actor_id);
        self.snapshots.remove(actor_id);
        debug!("Deleted all events and snapshots for actor {}", actor_id);
        Ok(())
    }
} 